<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
    <!-- 引入字体图标 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <!-- 引入Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <!-- 自定义样式 -->
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        .div {
            width: 400px;
            height: 500px;
            /* 实现整个框居中效果 */
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            overflow: hidden;
        }

        .head-div {
            width: 100px;
            height: 100px;
            border: 1px solid #999;
            border-radius: 50%;
            margin: 0 auto 10px auto;
            background-size: 100px 100px;
        }

        .sign-div {
            width: 400px;
            height: 300px;
            text-align: center;
            outline: none;
            border: 1px solid rgb(94, 92, 233);
            border-radius: 8px;
            background-color: rgba(172, 235, 243, .2);
            box-sizing: border-box;
        }

        .sign-div h1 {
            margin-bottom: 10px;
            color: rgb(29, 26, 26);
        }

        input {
            width: 250px;
            height: 44px;
            border: none;
            /* 元素周围的轮廓无效 */
            outline: none;
            /* 为元素指定的任何内边距和边框都将在已设定的宽度和高度内进行绘制 */
            box-sizing: border-box;
            display: block;
            padding: 0 16px;
        }

        .input-text {
            margin: 5px auto;
            border-radius: 16px;
        }

        .input-text:hover {
            border: 0.5px solid rgb(76, 76, 233);
            transition: 0.5s;
            border-radius: 4px;
        }

        .input-btn {
            margin: 30px auto 20px;
            border-radius: 44px;
            cursor: pointer;
            background-color: rgba(84, 175, 249, 0.8);
        }

        .input-btn:hover {
            color: #fff;
            font-size: 16;
            border-radius: 4px;
            transition: 0.5s;
            background-color: rgba(10, 138, 243, 0.8);
        }

        .sign-div a {
            text-decoration: none;
            color: rgb(92, 61, 112);
            font-size: 14px;
            padding: 10px;
            transition: 0.8s;
            display: block;
        }

        a:hover {
            color: #FFF;
            background: rgba(0, 0, 0, .3);
            border-radius: 8px;
        }
        /* 登录页面样式 */
        .container {
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f5f8fa;
            padding: 20px;
        }

        .login-box {
            width: 100%;
            max-width: 450px;
            padding: 30px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
        }

        .avatar-container {
            position: relative;
        }

        .avatar {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background-color: #54a5f5;
            background-size: cover;
            background-position: center;
            margin: 0 auto;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 40px;
            border: 3px solid white;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
        }

        .avatar-container h2 {
            font-weight: 600;
            color: #333;
        }

        .form-control {
            height: 46px;
            border-radius: 23px;
            padding: 0 20px;
            border: 1px solid #ddd;
            box-shadow: none;
            transition: all 0.3s;
        }

        .form-control:focus {
            border-color: #54a5f5;
            box-shadow: 0 0 0 3px rgba(84, 165, 245, 0.15);
            outline: none;
        }

        .form-control.is-invalid {
            border-color: #dc3545;
        }

        .form-group {
            margin-bottom: 20px;
            position: relative;
        }

        .form-group.focused .form-control {
            border-color: #54a5f5;
            box-shadow: 0 0 0 3px rgba(84, 165, 245, 0.15);
        }

        .btn-login {
            height: 46px;
            border-radius: 23px;
            background: linear-gradient(to right, #54a5f5, #0a8ab7);
            border: none;
            font-weight: 600;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .btn-login:hover {
            background: linear-gradient(to right, #3a8fd6, #087299);
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        }

        .btn-login i {
            margin-right: 8px;
        }

        /* 注册模态框样式 */
        #registerModal .modal-content {
            border-radius: 15px;
            border: none;
            box-shadow: 0 5px 30px rgba(0, 0, 0, 0.2);
        }

        #registerModal .modal-header {
            background-color: #f5f8fa;
            border-bottom: 1px solid #eee;
            padding: 20px;
        }

        #registerModal .modal-title {
            font-weight: 600;
            color: #333;
        }

        #registerModal .modal-body {
            padding: 25px;
        }

        #registerModal .modal-footer {
            border-top: 1px solid #eee;
            padding: 15px 25px;
        }

        #registerMessage {
            margin-bottom: 15px;
        }
    </style>
</head>

<body>
<div class="container">
    <div class="login-box">
        <div class="avatar-container text-center mb-4">
            <div class="avatar">
                <i class="fas fa-user-circle"></i>
            </div>
            <h2 class="mt-3">欢迎登录</h2>
        </div>

        <div class="login-form">
            <form id="loginForm">
                <div class="form-group has-feedback">
                    <input type="text" class="form-control" name="userName" placeholder="账号" required>
                    <div class="invalid-feedback">请输入账号</div>
                </div>
                <div class="form-group has-feedback">
                    <input type="password" class="form-control" name="password" placeholder="密码" required>
                    <div class="invalid-feedback">请输入密码</div>
                </div>
                <div class="form-group">
                    <button type="button" class="btn btn-primary btn-block btn-login" id="btn_login">
                        <i class="fas fa-sign-in-alt mr-2"></i>登录
                    </button>
                </div>
                <div class="form-group mt-3 text-center">
                    <p>还没有账号？<a href="#" id="btn_register">立即注册</a></p>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 注册模态框 -->
<div class="modal fade" id="registerModal" tabindex="-1" role="dialog" aria-labelledby="registerModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="registerModalLabel">用户注册</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="registerMessage" class="alert d-none"></div>
                <form id="registerForm">
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="username">用户名</label>
                            <input type="text" class="form-control" id="username" name="username" required>
                            <div class="invalid-feedback">请输入用户名</div>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="password">密码</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                            <div class="invalid-feedback">请输入密码</div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="truename">真实姓名</label>
                        <input type="text" class="form-control" id="truename" name="truename" required>
                        <div class="invalid-feedback">请输入真实姓名</div>
                    </div>

                    <div class="form-group">
                        <label for="gender">性别</label>
                        <select class="form-control" id="gender" name="gender" required>
                            <option value="">请选择性别</option>
                            <option value="0">男</option>
                            <option value="1">女</option>
                        </select>
                        <div class="invalid-feedback">请选择性别</div>
                    </div>

                    <div class="form-group">
                        <label for="age">年龄</label>
                        <input type="number" class="form-control" id="age" name="age" min="1" max="120" required>
                        <div class="invalid-feedback">请输入有效年龄(1-120)</div>
                    </div>

                    <div class="form-group">
                        <label for="address">地址</label>
                        <textarea class="form-control" id="address" name="address" rows="2" required></textarea>
                        <div class="invalid-feedback">请输入地址</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer justify-content-between">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="registerConfirmBtn">注册</button>
            </div>
        </div>
    </div>
</div>
<!-- 引入脚本 -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js"></script>
<script src="js/bootstrap-table.min.js"></script>
<script src="js/bootstrap-table-zh-CN.min.js"></script>
<script>
    // 统一的表单验证函数（与index页面保持一致）
   function validateField(field) {
       if (!field.val().trim()) {
           field.addClass('is-invalid');
           return false;
       } else {
           field.removeClass('is-invalid');
           return true;
       }
   }

   // 注册表单提交处理
   $('#registerForm').submit(function(e) {
       e.preventDefault();

       // 统一字段验证规则
       const fields = ['username', 'password', 'truename', 'gender', 'age', 'address'];
       let isValid = true;

       fields.forEach(field => {
           isValid &= validateField($(this).find(`#${field}`));
       });

       if (!isValid) return;

       // 发送统一格式的注册请求
       $.ajax({
           url: "user/save", // 与index页面接口统一
           type: 'POST',
           dataType: 'json',
           data: $(this).serialize(), // 自动序列化表单数据
           beforeSend: function() {
               $('#registerConfirmBtn').prop('disabled', true).html('注册中...');
           },
           success: function(result) {
               $('#registerMessage').removeClass('d-none alert-danger alert-success')
                   .addClass(result.status === 'success' ? 'alert-success' : 'alert-danger')
                   .text(result.message);

               if (result.status === 'success') {
                   setTimeout(() => {
                       $('#registerModal').modal('hide');
                       $('#registerForm')[0].reset();
                       $('#registerMessage').addClass('d-none');
                   }, 1500);
               } else {
                   $('#registerConfirmBtn').prop('disabled', false).html('注册');
               }
           },
           error: function() {
               $('#registerMessage').removeClass('d-none').addClass('alert-danger')
                   .text('服务器连接失败，请稍后再试');
               $('#registerConfirmBtn').prop('disabled', false).html('注册');
           }
       });
   });

   // 添加新脚本
   $(document).ready(function() {
        // 处理注册按钮点击事件
        $('#btn_register').click(function(e) {
            e.preventDefault();
            $('#registerModal').modal('show');
        });

       // 表单验证
       validateLoginForm();
       validateRegisterForm();

       // 输入框获得焦点效果
       $('.form-control').on('focus', function() {
           $(this).parent('.form-group').addClass('focused');
       }).on('blur', function() {
           $(this).parent('.form-group').removeClass('focused');
           validateField($(this));
       });

       // 实时验证字段
       $('.form-control').on('input', function() {
           validateField($(this));
       });

       // 密码确认验证
       $('#confirmPassword').on('input', function() {
           var password = $('#password').val();
           if ($(this).val() !== password) {
               $(this).addClass('is-invalid');
           } else {
               $(this).removeClass('is-invalid');
           }
       });
       // 输入框获得焦点效果
       $('.form-control').on('focus', function() {
           $(this).parent('.form-group').addClass('focused');
       }).on('blur', function() {
           $(this).parent('.form-group').removeClass('focused');
           validateField($(this));
       });

       // 添加缺失的注册按钮点击事件
       $('#btn_register').click(function(e) {
           e.preventDefault();
           $('#registerModal').modal('show');
       });
       // 处理模态框中的注册按钮点击事件
        $('#registerConfirmBtn').click(function() {
            $('#registerForm').submit();
        });

        // 注册表单提交处理
        function validateRegisterForm() {
            $('#registerForm').submit(function(e) {
                e.preventDefault();

                var isValid = true;
                $(this).find('.form-control').each(function() {
                    if (!validateField($(this))) {
                        isValid = false;
                    }
                });

                // 验证密码匹配
                var password = $('#password').val();
                var confirmPassword = $('#confirmPassword').val();
                if (password !== confirmPassword) {
                    $('#confirmPassword').addClass('is-invalid');
                    isValid = false;
                }

                if (isValid) {
                    register();
                }
            });
        }
   });

   function validateLoginForm() {
       $('#btn_login').click(function(e) {
           e.preventDefault();

           var isValid = true;
           $('#loginForm .form-control').each(function() {
               if (!validateField($(this))) {
                   isValid = false;
               }
           });

           if (isValid) {
               login();
           }
       });
   }

   function validateRegisterForm() {
       $('#registerForm').submit(function(e) {
           e.preventDefault();

           var isValid = true;
           $(this).find('.form-control').each(function() {
               if (!validateField($(this))) {
                   isValid = false;
               }
           });

           // 验证密码匹配
           var password = $('#password').val();
           var confirmPassword = $('#confirmPassword').val();
           if (password !== confirmPassword) {
               $('#confirmPassword').addClass('is-invalid');
               isValid = false;
           }

           if (isValid) {
               register();
           }
       });
   }

   function validateField(field) {
       if (!field.val()) {
           field.addClass('is-invalid');
           return false;
       } else {
           field.removeClass('is-invalid');
           return true;
       }
   }

   function login() {
       $.ajax({
           url: "login",
           data: $("#loginForm").serialize(),
           type: 'post',
           dataType: 'json',
           beforeSend: function() {
               $('#btn_login').prop('disabled', true);
               $('#btn_login').html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 登录中...');
           },
           success: function(data) {
               if(data.status == "success") {
                   // 保存用户信息到localStorage
                   if (data.data) {
                       localStorage.setItem('currentUser', JSON.stringify(data.data));
                   }
                   showToast('登录成功，即将跳转...', 'success');
                   setTimeout(function() {
                       window.location.href = "product.html";
                   }, 1500);
               } else {
                   showToast('登录失败：' + (data.message || '请检查账号密码'), 'error');
                   $('#btn_login').prop('disabled', false);
                   $('#btn_login').text('登录');
               }
           },
           error: function(xhr) {
               showToast('服务器连接失败，请稍后再试', 'error');
               $('#btn_login').prop('disabled', false);
               $('#btn_login').text('登录');
           }
       });
   }

   function register() {
       $.ajax({
           url: "user/save",
           type: 'post',
           dataType: 'json',
           data: $("#registerForm").serialize(),
           beforeSend: function() {
               $('#registerConfirmBtn').prop('disabled', true);
               $('#registerConfirmBtn').html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 注册中...');
           },
           success: function(result) {
               $('#registerMessage').removeClass('d-none alert-danger alert-success')
                   .addClass(result.status === 'success' ? 'alert-success' : 'alert-danger')
                   .text(result.message);

               if(result.status === 'success') {
                   setTimeout(function() {
                       $('#registerModal').modal('hide');
                       $('#registerForm')[0].reset();
                       $('#registerMessage').addClass('d-none');
                       showToast('注册成功！', 'success');
                   }, 1500);
               } else {
                   $('#registerConfirmBtn').prop('disabled', false);
                   $('#registerConfirmBtn').text('注册');
               }
           },
           error: function(xhr) {
               $('#registerMessage').removeClass('d-none alert-danger alert-success')
                   .addClass('alert-danger')
                   .text('服务器连接失败，请稍后再试');
               $('#registerConfirmBtn').prop('disabled', false);
               $('#registerConfirmBtn').text('注册');
           }
       });
   }

   function showToast(message, type) {
       var toastId = 'toast-' + Date.now();
       var bgColor = type === 'success' ? '#28a745' : '#dc3545';
       var iconClass = type === 'success' ? 'fas fa-check-circle' : 'fas fa-exclamation-circle';

       var toastHtml = `
           <div id="${toastId}" class="toast" style="position: fixed; top: 20px; right: 20px; z-index: 9999;">
               <div class="toast-header" style="background-color: ${bgColor}; color: white;">
                   <i class="${iconClass} mr-2"></i>
                   <strong class="mr-auto">${type === 'success' ? '成功' : '错误'}</strong>
                   <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
                       <span aria-hidden="true">&times;</span>
                   </button>
               </div>
               <div class="toast-body">
                   ${message}
               </div>
           </div>
       `;

       $('body').append(toastHtml);
       $(`#${toastId}`).toast({ delay: 3000 }).toast('show');

       // 自动移除toast元素
       setTimeout(function() {
           $(`#${toastId}`).remove();
       }, 3500);
   }
</script>
</body>
</html>
